/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.rest;

import javax.annotation.Resource;
import javax.ws.rs.ConsumeMime;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.ProduceMime;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geoscheduler.commons.msgs.ParametrizedMessage;
import org.geoscheduler.commons.msgs.types.AccountMsgs;
import org.geoscheduler.commons.msgs.types.TokenMsgs;
import org.geoscheduler.model.Account;
import org.geoscheduler.model.Token;
import org.geoscheduler.rest.utils.MIMEConstants;
import org.json.JSONObject;

/**
 * REST API for authorization tokens handling.
 * 
 * @author srakyi
 * @author lko - refactorings
 */
@Resource
@Path("tokens")
public class TokensResouce extends AbstractResource {

	private final Log LOG = LogFactory.getLog(TokensResouce.class);

	public TokensResouce() {
		super();
	}

	@POST
	@ConsumeMime(MIMEConstants.APP_JSON)
	@ProduceMime(MIMEConstants.APP_JSON)
	public JSONObject handlePost(JSONObject jsonAccount) {
		try {
			Account inAccount = getMarshaller().unmarshall(new Account(), jsonAccount);
			if (!getAuthProvider().checkCredentials(inAccount)) {
				return response(new ParametrizedMessage(TokenMsgs.CREDENTIALS_NOT_VALID));
			}

			Account account = getAccountDAO().loadByLogin(inAccount.getLogin());
			if (account == null) {
				return response(new ParametrizedMessage(AccountMsgs.LOGIN_NOT_FOUND, inAccount.getLogin()));
			}

			// we don't store passwd of some account types but we need it for generation of salt
			account.setPasswd(inAccount.getPasswd());
			Token token = Token.prepareTokenForAccount(account, getContext());
			getContext().getTokenDAO().insert(token);
			return response(token);
		} catch (Exception ex) {
			LOG.error("failed to create token for " + jsonAccount, ex);
			return response(ex);
		}
	}
}
